import {NextRequest, NextResponse} from "next/server";
import db from "@/lib/db";
import { Prisma } from "@prisma/client";
import {addDays, parseISO} from "date-fns";

export const GET = async (req: NextRequest) => {
  const searchParams = req.nextUrl.searchParams;
  // 获取分页参数
  const pageIndex = parseInt(searchParams.get('pageIndex') || '0');
  const pageSize = parseInt(searchParams.get('pageSize') || '10');
  // 计算跳过的记录数
  const skip = pageIndex * pageSize;

  const username = searchParams.get("username");
  const email = searchParams.get("email");
  const createdAt = searchParams.get("createdAt");
  const sex = searchParams.get("sex") === 'all' ? undefined : searchParams.get("sex");
  const status = searchParams.get("status") === 'all' ? undefined : searchParams.get("status");
  // 使用分页参数查询用户
  const condition:Prisma.UsersWhereInput={}
  //
  if(username){
    Object.assign(condition,{
      username:{
        contains:username
      }
    })
  }
  //
  if(email){
    Object.assign(condition,{
      email:{
        contains:email
      }
    })
  }
  //
  if(sex){
    Object.assign(condition,{
      sex:sex
    })
  }
  //
  if(sex){
    Object.assign(condition,{
      sex:sex
    })
  }
  //
  if(status){
    Object.assign(condition,{
      status:status
    })
  }

  if(createdAt){
    const {from, to} = JSON.parse(decodeURIComponent(createdAt));

    const createAtCondition = {};
    if (from) {
      Object.assign(createAtCondition, {
        gte: parseISO(from)
      })
    }

    if (to) {
      Object.assign(createAtCondition, {
        lt: addDays(parseISO(to),1)
      })
    }

    condition.createdAt = createAtCondition;
  }


  const users = await db.users.findMany({
    where: condition,
    skip: skip,
    take: pageSize,
  });

  //总数
  const count = await db.users.count({
    where: condition
  });

  const us = users.map((it) => {

    return {
      username: it.username,
      sex: it.sex,
      email: it.email,
      status: it.status,
      userId: it.userId,
      createdAt: it.createdAt,
      updatedAt: it.updatedAt
    };
  });

  return NextResponse.json({
    code: 200,
    msg: "成功",
    data: {
      // 这里可以替换为实际的总记录数查询
      rowCount: count,
      data: us,
      pageIndex: pageIndex,
      pageSize: pageSize,
    }
  });
}


export const DELETE = async (request:Request) => {

  try{
    const userIds:Array<number> = await request.json();
    await db.users.deleteMany({
      where:{
        userId:{
          in:userIds
        }
      }
    })
  }catch {
    return NextResponse.json({
      code: 500,
      msg:"系统异常"
    });
  }
  return NextResponse.json({
    code: 200,
    msg:"删除成功"
  })
}